<template>
  <div class="common-layout">
    <el-container class="container">
      <el-header class="header">
        <div class="header-row">
          &nbsp;&nbsp;项目名称 :&nbsp;&nbsp; <el-input v-model="projectName" style="width: 200px; margin-right: 10px;" placeholder="请输入项目名称" />
          &nbsp;&nbsp;时间 : <el-date-picker
            v-model="startAndEndDate"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            unlink-panels
            style="margin-right: 80px;margin-left: 20px"
            class="date-picker-width"
        >
          <template #prev-month>
            <el-icon><CaretLeft /></el-icon>
          </template>
          <template #next-month>
            <el-icon><CaretRight /></el-icon>
          </template>
          <template #prev-year>
            <el-icon>
              <svg
                  viewBox="0 0 20 20"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
              >
                <g stroke-width="1" fill-rule="evenodd">
                  <g fill="currentColor">
                    <path
                        d="M8.73171,16.7949 C9.03264,17.0795 9.50733,17.0663 9.79196,16.7654 C10.0766,16.4644 10.0634,15.9897 9.76243,15.7051 L4.52339,10.75 L17.2471,10.75 C17.6613,10.75 17.9971,10.4142 17.9971,10 C17.9971,9.58579 17.6613,9.25 17.2471,9.25 L4.52112,9.25 L9.76243,4.29275 C10.0634,4.00812 10.0766,3.53343 9.79196,3.2325 C9.50733,2.93156 9.03264,2.91834 8.73171,3.20297 L2.31449,9.27241 C2.14819,9.4297 2.04819,9.62981 2.01448,9.8386 C2.00308,9.89058 1.99707,9.94459 1.99707,10 C1.99707,10.0576 2.00356,10.1137 2.01585,10.1675 C2.05084,10.3733 2.15039,10.5702 2.31449,10.7254 L8.73171,16.7949 Z"
                    />
                  </g>
                </g>
              </svg>
            </el-icon>
          </template>
          <template #next-year>
            <el-icon>
              <svg
                  viewBox="0 0 20 20"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
              >
                <g stroke-width="1" fill-rule="evenodd">
                  <g fill="currentColor">
                    <path
                        d="M11.2654,3.20511 C10.9644,2.92049 10.4897,2.93371 10.2051,3.23464 C9.92049,3.53558 9.93371,4.01027 10.2346,4.29489 L15.4737,9.25 L2.75,9.25 C2.33579,9.25 2,9.58579 2,10.0000012 C2,10.4142 2.33579,10.75 2.75,10.75 L15.476,10.75 L10.2346,15.7073 C9.93371,15.9919 9.92049,16.4666 10.2051,16.7675 C10.4897,17.0684 10.9644,17.0817 11.2654,16.797 L17.6826,10.7276 C17.8489,10.5703 17.9489,10.3702 17.9826,10.1614 C17.994,10.1094 18,10.0554 18,10.0000012 C18,9.94241 17.9935,9.88633 17.9812,9.83246 C17.9462,9.62667 17.8467,9.42976 17.6826,9.27455 L11.2654,3.20511 Z"
                    />
                  </g>
                </g>
              </svg>
            </el-icon>
          </template>
        </el-date-picker>
          <el-button :icon="Search" type="primary" @click="getGenerateProjectsByCondition" style="margin-right: 10px">搜索</el-button>
          <el-button :icon="RefreshRight" type="info" @click="resetData" style="margin-right: 200px">重置</el-button>
        </div>

      </el-header>
      <el-header style="height: 14px"/>
      <el-main class="main">
        <div class="project-list">
          <project-card
              v-for="project in projects"
              :key="project.id"
              :project="project"
              @view="viewProject(project.projectId)"
              @export="downloadReport(project.projectId)"
          />
        </div>

      </el-main>
    </el-container>
  </div>

  <transition name="expand">
    <div v-if="showDetail" style="height: 700px" class="detail-content">
      <h2>软件造价评估报告·智能助手 <el-icon color="#409EFF"><ChromeFilled /></el-icon></h2>
      <el-divider></el-divider>
      <el-row :gutter="20">
        <el-col :span="11">
          <div class="pdf-container">
            <VueOfficeDocx :src="projectUrl" style="height: 560px;width: 95%"/>
          </div>
        </el-col>
        <el-divider :span="1" direction="vertical" content-position="center"></el-divider>
        <el-col :span="11">
          <div class="questions">
            <div class="chat-messages">
              <div v-for="(msg, index) in messages" :key="index" class="chat-message" :class="{ 'user-message': msg.sender === 'user' }">
                <div class="message-content">
                  <!-- 使用 MarkdownRenderer 渲染带有 Markdown 的消息 -->
                  <MarkdownRenderer :markdown="msg.content" v-if="msg.isMarkdown" />
                  <div v-else>{{ msg.content }}</div>
                </div>
              </div>
            </div>
            <el-form @submit.prevent="sendMessage">
              <el-input
                  v-model="message"
                  placeholder="请输入消息..."
                  type="textarea"
                  :rows="4"
              ></el-input>
              <el-button
                  type="primary"
                  @click="sendMessage"
                  style="margin-left: auto; margin-right: 10px; display: block;margin-top: 5px"
              >
                发送
              </el-button>
            </el-form>
          </div>
        </el-col>
      </el-row>
      <el-button @click="downloadReport(projectUrl)" style="margin-right: 100px" class="close-button" type="primary" size="large">下载</el-button>
      <el-button @click="closeDialog" class="close-button" type="primary" size="large">关闭</el-button>
    </div>
  </transition>

</template>


<script setup lang="ts">
import {CaretLeft, CaretRight, ChromeFilled, RefreshRight, Search} from "@element-plus/icons-vue";
import { ref } from "vue";

import ProjectCard from "../../components/Report/ProjectCard.vue";
import MarkdownRenderer from "../../components/Report/MarkdownRenderer.vue";

import { useUserStore } from "../../stores/UserStore.ts";
import {
  getAiAnswer,
  getGenerateProjectsByConditionAsync,
  getGenerateReportProjectById,
  getReportProjectForGenerate
} from "../../api/Report/projectData.ts";
import { ElMessage, ElLoading } from "element-plus";
import VueOfficeDocx from "../../components/Report/VueOfficeDocx.vue";



const tenantId = useUserStore().userInfo.tenantId;

// 项目数据
const handleData = (res:any) => {
  for (let i = 0; i < res.projects.length; i++) {
    if (projects.value[i] == null) {
      projects.value[i] = {};
    }
    projects.value[i].projectId = res.projects[i].projectId;
    projects.value[i].projectName = res.projects[i].projectName;
    projects.value[i].amount = res.projects[i].cost;
    projects.value[i].status = res.projects[i].projectStatus;
    projects.value[i].createTime = res.projects[i].createTime.replace("T", " ");
    projects.value[i].completeTime = res.projects[i].updateTime.replace("T", " ");
    projects.value[i].remark = res.projects[i].remark;
  }
};

const projects = ref<any>([]);
const getGenerateReportProject = async () => {
  const res = await getReportProjectForGenerate(tenantId);
  console.log(res);
  if (res.projects.length == 0) {
    ElMessage.warning("可查看报告为空");
    return;
  }
  handleData(res);
};

getGenerateReportProject();

// 条件查询
const projectName = ref<string>();
const projectStatus = ref<string>();
const startAndEndDate = ref('');



const getGenerateProjectsByCondition = async () => {

  const startDate=startAndEndDate.value[0];
  const endDate= startAndEndDate.value[1];
  let params = {
    tenantId: tenantId,
    projectName: projectName.value ? projectName.value : "",
    startTime: startDate ? startDate : null,
    endTime: endDate ? endDate : null,
  };

  const res = await getGenerateProjectsByConditionAsync(params);
  if (res.projects.length == 0) {
    ElMessage.warning("无数据");
    return;
  }
  projects.value=[]

  handleData(res)
};

// 清空数据
const resetData = () => {
  projectName.value = "";
  projectStatus.value = "";
  startAndEndDate.value = "";
  getGenerateReportProject()
};

// 处理“查看”操作
const projectUrl = ref("");
const showDetail = ref(false);
const AiId = ref("");
const viewProject = async (projectId:any) => {
  showDetail.value = true;
  const res = await getGenerateReportProjectById(projectId);
  projectUrl.value = res.url;
  AiId.value = res.aiId;
};

const closeDialog = () => {
  showDetail.value = false;
};

// AI问答部分
const message = ref("");
const messages = ref([{ content: "你好，我是AI助手，请问有什么可以帮助您的吗？", sender: "ai" }]);

const loadingInstance = ref<any>(null); // 用于存储加载提示实例

// 向后端获取AI回答
const getAiAnswerAsync = async (userMsg: string) => {
  try {
    const res = await getAiAnswer(AiId.value, userMsg);
    if (res?.data.answer) {
      // 将AI返回的Markdown格式消息转化为HTML
      messages.value.push({ content: res.data.answer, sender: "ai", isMarkdown: true });
    } else {
      messages.value.push({ content: "AI暂时无法回答这个问题。", sender: "ai", isMarkdown: false });
    }
  } catch (error) {
    messages.value.push({ content: "发生错误，请稍后再试。", sender: "ai", isMarkdown: false });
    ElMessage.error("获取AI答案失败");
  } finally {
    loadingInstance.value.close(); // 关闭加载提示
  }
};

// 发送消息
const sendMessage = () => {
  if (message.value.trim() !== "") {
    messages.value.push({ content: message.value, sender: "user", isMarkdown: false });

    // 显示加载提示
    loadingInstance.value = ElLoading.service({
      lock: true,
      text: "AI 正在思考...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    // 清空输入框
    const userMsg = message.value;
    message.value = "";

    // 获取AI回答
    getAiAnswerAsync(userMsg);
  }
};
const generateRandomFileName = () => {
  const date = new Date();
  const dateString = date.toISOString().replace(/:/g, '-');
  const randomString = Math.random().toString(36).substring(2, 15);
  return `${dateString}-${randomString}.docx`;
};
// 处理“导出”操作

const downloadReport =async (projectId) => {
  const res = await getGenerateReportProjectById(projectId);
  const url = res.url;
  fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.blob();
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = generateRandomFileName(); // 设置下载文件名
        a.click();
        window.URL.revokeObjectURL(url); // 释放URL对象
      })
      .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
      });
};


</script>

<style scoped>

.common-layout{
  width: 100%;
  height: 86%;
  border-radius: 8px;
}
.container {
  border-radius: 10px;
}
.header {
  height: 100px;
  background-color: #FFFFFF;
  border-radius: 10px;
  color: black;
  padding: 10px;
}
.date-picker-width {
  width: 200px !important;
}


.header-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 20px;
  margin-bottom: 10px;
}

.header-row:last-child {
  margin-bottom: 0;
}

.main {
  background-color: #FFFFFF;
  border-radius: 10px;
  color: #1a1a1a;
}
.project-list {
  display: flex;
  flex-wrap: wrap;
  gap: 1%;
  justify-content: flex-start;
  padding: 2px;
  margin-left: -1%;

}

.project-list > * {
  flex: 1 1 calc(33.33% - 1%);
  max-width: calc(33.33% - 1%);
  box-sizing: border-box;
  margin-bottom: 20px;

}
.detail-content {
  position: fixed;
  top: 5%;
  left: 5%;
  width: 90%;
  height: 90%;
  background-color: #fff;
  z-index: 1000;
  padding: 20px;
  overflow: auto;
  border-radius: 12px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
  transform: scale(1);
  opacity: 1;
  transition: all 0.5s ease;
}
.pdf-container {
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.questions {
  padding: 10px;
}


.close-button {
  position: absolute;
  top: 20px;
  right: 20px;
}

.chat-messages {
  margin-top: 20px;
  height: 400px;
  overflow-y: auto;
}

.chat-message {
  display: flex;
  justify-content: start;
  margin-bottom: 10px;
}

.el-loading-mask {
  z-index: 2000; /* 确保加载提示在所有内容之上 */
}

.message-content {
  max-width: 80%;
  padding: 10px;
  border-radius: 5px;
  background-color: #f3f3f3;
}

.chat-message:not(.user-message) .message-content {
  background-color: #d1e7ff;
  align-self: flex-start;
  padding: 10px;
  border-radius: 5px;
}

.user-message .message-content {
  background-color: #c2f0c2;
  align-self: flex-end;
  margin-left: auto;
  padding: 10px;
  border-radius: 5px;
}
</style>

